package it.fantacalcio.hibernate.dao;

import it.fantacalcio.model.Squadra;
import it.fantacalcio.model.User;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;

public class SquadraDAOImpl extends BaseHibernateDAO implements SquadraDAO {

	@Override
	public void save(Squadra squadra) throws Exception {
		getSession().save(squadra);
	}
	
	@Override
	public void delete(Squadra squadra) throws Exception {
		getSession().delete(squadra);
	}
	
	@Override
	public void update(Squadra squadra) throws Exception {
		getSession().saveOrUpdate(squadra);		
	}

	@Override
	public Squadra get(Long id) throws Exception {
		return (Squadra) getSession().get(Squadra.class, id);
	}
	@Override
	@SuppressWarnings("unchecked")
	public Squadra getByUser(User user) throws Exception {
		Criteria cri = getSession().createCriteria(Squadra.class);
		cri.add(Restrictions.eq("presidente", user));
		List<Squadra> results = cri.list();
		if (results.size()==0){
			return null;
		}
		return results.get(0) == null ? null : results.get(0);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Squadra> list() throws Exception {
		String queryString = "from Squadra";
		Query queryObject = getSession().createQuery(queryString);
		return queryObject.list();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Squadra> findByExample(Squadra squadra) throws Exception {
		Criteria cri = getSession().createCriteria(Squadra.class);
		cri.add(Example.create(squadra).ignoreCase());
		if(squadra.getPresidente()!=null){
			cri.add(Restrictions.eq("presidente", squadra.getPresidente()));
		}
		List<Squadra> results = cri.list();
		return results;
	}

}
